/**
 * The Censorship class is a censorhsip utility developed for the CIA.
 * @author Jane Doe
 * @version 0.1 March 6, 2013.
 */
package meltwater.cia;

import java.util.ArrayList;
import java.io.*;
import java.util.Scanner;

public class Censorship {

   /**
    * Censors a document
    * @param toCensor the keywords and phrases to replace with "XXXX"
    * @param document the document to do the replacing in
    * @return a new document that is censored
    */
    public String censor( String toCensor, String document ) {
        ArrayList<String> words = getWords( toCensor );
        return replaceSR( words, document );
    }

   /**
    * Gets keywords and phrases from a string 
    * @param toCensor the string containing all of the keywords and passphrases
    * @return an arraylist of the phrases and keywords
    */
    private ArrayList<String> getWords( String toCensor ) {
        ArrayList<String> words = new ArrayList<String>();
        
        Scanner scanner = new Scanner( toCensor );
        scanner.useDelimiter( "\\s|\\,\\s" );

        while( scanner.hasNext() ) {
            String ret = scanner.next();
            // check for phrase instead of a keyword
            if( ret.startsWith("\"") || ret.startsWith("\'") ) {
                while( scanner.hasNext() && !ret.endsWith("\"") && !ret.endsWith("\'")  ) {
                    String n = scanner.next();
                    ret += " " + n;
                }
                ret = ret.replace( "\"", "" );
                ret = ret.replace( "\'", "" );
            }
            words.add( ret );
        }

        return words;
    }

   /**
    * Returns a censored string 
    * @param toReplace ArrayList containing all of the keywords and passphrases
    * @param document the document to do the replaceing in
    * @return a string that has been censored
    */
    private String replaceSR( ArrayList<String> toReplace, String document ) {
        String toRet = new String(document);
        for( String cur : toReplace ) {
            toRet = toRet.replaceAll( cur, "XXXX" );
            // toRet = toRet.replaceAll( "(?i)"+cur, "XXXX" );  // case insensative
        }
        return toRet;
    }

}
